import { ConfigEnv, defineConfig, UserConfigExport,loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { svgBuilder } from './src/plugins/svgBuilder'
import { configMockPlugin } from './src/plugins/configMockPlugin'
import { configSvgIconsPlugin } from './src/plugins/configSvgIconsPlugin'
import { configStyleImportPlugin } from './src/plugins/configStyleImportPlugin'
import { configHtmlPlugin } from './src/plugins/configHtmlPlugin'
import { configCompressPlugin } from './src/plugins/configCompressPlugin'
import {wrapperEnv} from './src/utils/env'
import styleImport from 'vite-plugin-style-import'

const resolve = (dir: string) => path.join(__dirname, dir)

// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  const isBuild = command === 'build'
  const root = process.cwd()
  const env = loadEnv(mode,root)
  const ViteEnv = wrapperEnv(env)
  const {
    VITE_PORT,
    VITE_USE_MOCK,
    VITE_BUILD_COMPRESS,
    VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE

  } = ViteEnv
  return defineConfig({
    plugins: [
      vue(),
      // svgBuilder('./src/assets/icons/svg/'),
      configMockPlugin(isBuild), // mock 模拟请求
      configSvgIconsPlugin(isBuild),
      configStyleImportPlugin(isBuild),
      configHtmlPlugin(ViteEnv, isBuild),
      configCompressPlugin( VITE_BUILD_COMPRESS, VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE)
      // styleImport({
      //   libs: [
      //     {
      //       libraryName: 'element-plus',
      //       esModule: true,
      //       ensureStyleFile: true,
      //       resolveStyle: name => {
      //         name = name.slice(3)
      //         return `element-plus/packages/theme-chalk/src/${name}.scss`
      //       },
      //       resolveComponent: name => {
      //         return `element - plus / lib / ${name}`
      //       }
      //     }
      //   ]
      // }),
    ],
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    server: {
      host: '',
      port: 8088,
      strictPort: false, // 尝试下一个可以端口
      open: false,
      proxy: {
        '/api': {
          target: 'http://localhost:9999',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, '')
        }
      }
    }
  })
}
